/* 
    Copyright (c) 2011 Microsoft Corporation.  All rights reserved.
    Use of this sample source code is subject to the terms of the Microsoft license 
    agreement under which you licensed this sample source code and is provided AS-IS.
    If you did not accept the terms of the license agreement, you are not authorized 
    to use this sample source code.  For the terms of the license, please see the 
    license agreement between you and Microsoft.
  
    To see all Code Samples for Windows Phone, visit http://go.microsoft.com/fwlink/?LinkID=219604 
  
*/

using System;
using System.Windows;
using System.Windows.Threading;
using System.Windows.Media;
using Microsoft.Phone.Shell;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using TagCloudNewsLibrary;

namespace TagCloudNews
{
    public partial class MainPage : PhoneApplicationPage
    {
        PeriodicTask _tilePeriodicTask;
        DispatcherTimer _dispatcherTimer = new DispatcherTimer();

        private bool _loaded;

        const string _tileTaskName = "AltMusicNewsPeriodicAgent";
        const string _periodicTaskDesc = "Alt Music News background refresh task.";

        // Constructor
        public MainPage()
        {
            InitializeComponent();

            //set up system tray
            var prog = new ProgressIndicator();
            prog.IsIndeterminate = true;

            SystemTray.SetIsVisible(this, true);
            SystemTray.SetProgressIndicator(this, prog);

            // Subscribe to the DownloadStringCompleted event prior to downloading the RSS feed.
            TagDataService.Current.LoadCompletedEvent = new LoadCompletedEventHandler(LoadCompleted);
            TagDataService.Current.LoadFailedEvent = new LoadFailedEventHandler(LoadFailed);

            //set up the timer that monitors the scroll position
            _dispatcherTimer.Tick += new EventHandler(getVScrollPosition);
            _dispatcherTimer.Interval = new TimeSpan(0, 0, 1);

            //start the background agent
            StartPeriodicAgent(_tileTaskName);
        }

        // This method determines whether the user has navigated to the application after the application was tombstoned.
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (!_loaded)
            {
                RefreshFeed();
                _loaded = true;
            }
            else
            {           
                string h = TagDataService.Current.GetHtml();

                HTML.NavigateToString(h);
            }
        }

        private void StartPeriodicAgent(string taskName)
        {
            // Obtain a reference to the period task, if one exists
            _tilePeriodicTask = ScheduledActionService.Find(taskName) as PeriodicTask;

            // If the task already exists and background agent is enabled for the
            // app, remove the task and then add it again to update 
            // the schedule.
            if (_tilePeriodicTask != null)
            {
                ScheduledActionService.Remove(taskName);
            }
            _tilePeriodicTask = new PeriodicTask(taskName);

            // The description is required for periodic agents. This is the string that the user
            // will see in the background services Settings page on the phone.
            _tilePeriodicTask.Description = _periodicTaskDesc;

            // Place the call to add a periodic agent. This call must be placed in 
            // a try block in case the user has disabled agents.
            try
            {
                ScheduledActionService.Add(_tilePeriodicTask);

                // If debugging is enabled, use LaunchForTest to launch the agent in one minute.
#if(DEBUG)
                ScheduledActionService.LaunchForTest(taskName, TimeSpan.FromSeconds(60));
#endif
            }
            catch (InvalidOperationException)
            {
                //if (exception.Message.Contains("BNS Error: The action is disabled"))
                //{
                //    MessageBox.Show("Background agents for this application have been disabled by the user.");
                //}
                //else if (exception.Message.Contains("BNS Error: The maximum number of ScheduledActions of this type have already been added."))
                //{
                //    // No user action required. The system prompts the user when the hard limit of periodic tasks has been reached.
                //    MessageBox.Show("BNS Error: The maximum number of ScheduledActions of this type have already been added.");
                //}
                //else
                //{
                //    MessageBox.Show("An InvalidOperationException occurred.");
                //}
            }
            catch (SchedulerServiceException)
            {
                // No user action required.
            }
            finally
            {
            }
        }

        public void RefreshFeed()
        {
            PrepareUIForReload();

            TagDataService.Current.RefreshNewsFeed(false);
        }

        private void PrepareUIForReload()
        {
            HTML.Visibility = System.Windows.Visibility.Collapsed;
            SystemTray.BackgroundColor = Colors.Green;
            SystemTray.ForegroundColor = Colors.White;
            SystemTray.ProgressIndicator.IsVisible = true;
            SystemTray.SetIsVisible(this, true);
            SystemTray.ProgressIndicator.Text = "Fetching the news";
        }

        public void LoadCompleted()
        {
            string h = TagDataService.Current.GetHtml();

            HTML.NavigateToString(h);
        }

        public void LoadFailed()
        {
            //reload failed
            MessageBox.Show("Load failed.  Try again later");
        }

        private void HTML_Navigating(object sender, NavigatingEventArgs e)
        {
            HTML.Visibility = System.Windows.Visibility.Collapsed;

            e.Cancel = true;
            NavigationService.Navigate(new Uri("/StoriesPage.xaml?tag=" + TagDataService.Current.EscapeTag(e.Uri.LocalPath), UriKind.Relative));
        }

        private void HTML_LoadCompleted(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            SystemTray.ProgressIndicator.IsVisible = false;
            SystemTray.SetIsVisible(this, false);

            HTML.Visibility = System.Windows.Visibility.Visible;

            setVScrollPosition();

            _dispatcherTimer.Start();
        }

        private void RefreshButton_Click(object sender, EventArgs e)
        {
            PrepareUIForReload();
            TagDataService.Current.ForceReload();
        }

        private void RefreshMenu_Click(object sender, EventArgs e)
        {
            PrepareUIForReload();
            TagDataService.Current.ForceReload();
        }

        private void ReadAllMenu_Click(object sender, EventArgs e)
        {
            TagDataService.Current.ReadAllStories();

            string h = TagDataService.Current.GetHtml();

            HTML.NavigateToString(h);
        }

        private void AboutMenu_Click(object sender, EventArgs e)
        {
            if (HTML.Visibility==System.Windows.Visibility.Visible)
            {
                NavigationService.Navigate(new Uri("/About.xaml", UriKind.Relative));
            }
        }

        private void setVScrollPosition()
        {
            try
            {
                HTML.InvokeScript("setVerticalScrollPosition", TagDataService.Current.GetScrollPos().ToString());
            }
            catch (Exception)
            {
            }
        }

        private void getVScrollPosition(object sender, EventArgs e)
        {
            try
            {
                //int i;
                string js = HTML.InvokeScript("getVerticalScrollPosition") as string;
                int i;
                bool result = Int32.TryParse(js, out i);
                if(result)
                {
                    TagDataService.Current.SetScrollPos(i);
                }
            }
            catch (Exception)
            {
            }
        }
    }
}
